# This file is part of Neuroinfo Toolkit.
#
# Neuroinfo Toolkit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Neuroinfo Toolkit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Neuroinfo Toolkit.  If not, see <http://www.gnu.org/licenses/>.

from neuro.base import Object
from neuro.filesystem import *
from neuro.models.dicom import *
from neuro.exceptions import IllegalArgumentException

class DicomScanner(Object):
	'''
	DICOM scanner
	'''

	@staticmethod
	def scan(dir, recursive=True, checkFormat=True):
		'''
		Import DICOM files from directory and return a dict of DicomSession objects ::
		
			>>> listing = DicomScanner.scan("/path/to/dicoms")
			{'1.3.12.2.1107.5.2.32.35380.30000011102718412821800000004': <neuro.models.dicom.DicomSession object at 0x7fe137027950>, ...}

		:param dir: Input directory
		:type dir: str
		:param recursive:
		:type recursive: bool
		:returns: {study_uid: :class:`~neuro.models.dicom.DicomSession`}
		:rtype: dict
		'''
		if(not isinstance(dir, basestring)):
			raise IllegalArgumentException("Directory must be an instance of str")

		dir = dir.strip()

		if(dir == ""):
			raise IllegalArgumentException("Directory cannot be empty")

		sessions = {}
		
		contents = dirList(dir, recursive, Dicom)

		if(len(contents) == 0):
			return sessions

		for file in contents:
			dicom = Dicom(file, checkFormat=checkFormat)

			if(not dicom.getStudyUID() in sessions):
				sessions[dicom.getStudyUID()] = DicomSession()

			sessions[dicom.getStudyUID()].addImage(dicom)

		return sessions
